<?php

namespace app\common\model\points_mall;

use addons\xyb\XypHelper;
use app\common\model\daily\UsersModel;
use app\common\model\marketing\MarketingCoupons;
use app\common\model\Goods as ProductGoods;
use app\common\model\marketing\UsersMarketingCoupons;
use app\common\model\Scenic;
use think\Db;
use think\Exception;
use think\Model;

class Orders extends Model
{
    // 数据库
    protected $name = 'points_mall_orders';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /*
     * status
     * 0:待支付;1:已兑换；2：已使用；3：已退还；4：已过期
     * */
    // 追加属性
//    protected $append = [
//        'status_text',
//        'create_date'
//    ];

    public function getStatusTextAttr($value, $data)
    {
        if (!isset($data['status']) || !$data['status']) {
            return [];
        }
        switch ($data['status']) {
            case '1':
                return ['color' => 'success', 'label' => '已兑换'];
                break;
            case '2':
                return ['color' => 'magenta', 'label' => '已使用'];
                break;
            case '3':
                return ['color' => 'orange', 'label' => '已退还'];
                break;
            case '4':
                return ['color' => 'error', 'label' => '已过期'];
                break;
        }
    }

    public function getPayDateAttr($value, $data)
    {
        if(!$value) return '';
        return date('Y-m-d H:i:s', $value);
    }

    public function getRefundDateAttr($value, $data)
    {
        if(!$value) return '';
        return date('Y-m-d H:i:s', $value);
    }

    public function getUseDateAttr($value, $data)
    {
        if(!$value) return '';
        return date('Y-m-d H:i:s', $value);
    }
    public static function getAdminLists(){
        $keyword = request()->param('keyword', '');
        $goods_type = request()->param('goods_type', '');
        $category_id = request()->param('category_id', '');
        $grant_status = request()->param('status');
        $pay_date = request()->param('pay_date');

        $field = 'id,order_no,goods_id,users_id,category_id,category_id as category_name,goods_type,goods_name,payment_type,
        point_amount,youth_amount,status,status as status_text,pay_time as pay_date,pay_status,refund_time as refund_date,use_time as use_date';
        $query = self::field($field)->where('pay_status', 10);
        if ($keyword) {
            $query->where(function ($query)use($keyword){
                $query->where('users_id', 'like', '%'.$keyword.'%')
                    ->whereOr('order_no', 'like', '%'.$keyword.'%')
                    ->whereOr('goods_name', 'like', '%'.$keyword.'%');
            });
        }
        if ($goods_type) {
            $query->where('goods_type', $goods_type);
        }
        if ($category_id) {
            $query->where('category_id', $category_id);
        }
        if ($grant_status) {
            $query->where('status', $grant_status);
        }
        if ($deadline_arr = XypHelper::stringToArray($pay_date)) {
            $query->where('pay_time','>',  XypHelper::getTimestamp($deadline_arr[0]))
                ->where('pay_time','<',  XypHelper::getTimestamp($deadline_arr[1]));
        }

        if ($grant_status) {
            $query->where('status', $grant_status);
        }
        return $query->order('id desc')->paginate(10);
    }


    public function getCategoryNameAttr($value, $data)
    {
        if (!isset($data['category_id']) || !$data['category_id']) {
            return '';
        }
        return Category::where('id', $data['category_id'])->value('name');
    }

    public static function getGoodsInfoAttr($value, $data)
    {
        if(!isset($data['goods_id']) && !$data['goods_id']){
           return [];
        }
        if(!$goods_info = Goods::field('id,name,cover,reward_coupons_id')->where('id', $data['goods_id'])->find()){
            return [];
        }
        $goods_info->cover = cdnurl($goods_info->cover);
        return $goods_info;
    }
    public static function getUsersExchangeNumber($users_id, $goods_id)
    {
        return self::where('users_id', $users_id)->where('goods_id', $goods_id)
            ->where('pay_status', 10)->count('id');
    }

    /*获取商品今日兑换数量*/
    public static function getGoodsTodaysExchangeNumber($goods_id)
    {
        return self::where('goods_id', $goods_id)->where('pay_status', 10)->where('pay_time', '>=', strtotime('Y-m-d'))->count('id');
    }
    public static function getUsersExchangeRecentlyDate($users_id, $goods_id)
    {
        return self::where('users_id', $users_id)->where('goods_id', $goods_id)
            ->where('pay_status', 10)->order('id desc')->value('pay_time');
    }

    /*获取用户指定天数内兑换的次数*/
    public static function getUsersSpecifyDateExchangeNumber($users_id, $goods_id, $date_time)
    {
        return self::where('users_id', $users_id)->where('goods_id', $goods_id)
            ->where('pay_status', 10)->where('pay_time', '>', $date_time)
            ->order('id desc')->count('id');
    }


    public static function createGoodsOrder($goods, $users_id)
    {
        try {
            $forms = [
                'order_no'         => XypHelper::xyb_get_order_no(),
                'users_id'         => $users_id,
                'goods_id'         => $goods['id'],
                'goods_type'       => $goods['goods_type'],
                'goods_name'       => $goods['name'],
                'category_id'      => $goods['category_id'],
                'payment_type'     => $goods['payment_type'],
                'point_amount'     => $goods['point_amount'],
                'youth_amount'     => $goods['youth_amount'],
                'purchase_amount'  => $goods['purchase_amount'],
                'deadline'         => time()+(intval($goods['deadline'])*86400),
                'status'           => 0,
                'pay_status'       => 0,
                'createtime'       => time(),
                'pay_time'         => 0,
            ];
            return self::create($forms);
        } catch (\Exception $e) {
            return false;
        }
    }


    public static function distributeExchangeGoods($goods, $users_id)
    {
        $response = ['goods_type' => $goods['goods_type'], 'record_id' => 0];
        if($goods['goods_type'] == 1){
            if(!$reward_coupons_id = XypHelper::formatJsonStringToArray($goods['reward_coupons_id'])){
                return false;
            }
            $field = 'id,expiration_method,use_end_time,effective_days,type';
            $coupon = MarketingCoupons::field($field)->where('id', $reward_coupons_id['id'])->find();
            $attach = ['order_id' => $goods['order_id']];
            /*兑换奖励*/
            $response['record_id'] = UsersMarketingCoupons::usersJobsReceiveCoupons($users_id, $coupon, 3, $attach);
        }
        return $response;
    }



    public static function usersExchangeLists($users_id, $page, $limit){
        $field = 'id,order_no,goods_type,goods_id,goods_id as goods_info,payment_type,point_amount,
        youth_amount,status,pay_status,pay_time,deadline';
        $order_lists = self::field($field)->where('users_id', $users_id)
            ->where('pay_status', 10)->where('status', '>', 0)
            ->page($page, $limit)
            ->order('id desc')
            ->paginate();
        if(!$order_lists->items()){
            return $order_lists;
        }
        foreach ($order_lists as $key => $value){
            $order_lists[$key]['pay_time'] = date('Y-m-d H:i:s', $value['pay_time']);
            $order_lists[$key]['payment_method'] = self::getOrderPaymentMethod($value);
            if($value['status'] == 1 && $value['deadline'] && $value['deadline'] < time()){
                $order_lists[$key]['status'] = 4;
            }
        }
        return $order_lists;
    }

    public static function usersExchangeDetails($order_id){
        $field = 'id,order_no,goods_type,goods_id,goods_id as goods_info,payment_type,point_amount,
        youth_amount,status,pay_status,pay_time,deadline,refund_time,use_time';
        if(!$order_info = self::field($field)->where('id', $order_id)->find()){
            return [];
        }
        $order_info['pay_time'] = date('Y-m-d H:i:s', $order_info['pay_time']);
        if($order_info['refund_time']){
            $order_info['refund_time'] = date('Y-m-d H:i:s', $order_info['refund_time']);
        }
        if($order_info['use_time']){
            $order_info['use_time'] = date('Y-m-d H:i:s', $order_info['use_time']);
        }
        if($order_info['deadline']){
            $order_info['deadline'] = date('Y-m-d H:i:s', $order_info['deadline']);
        }
        $order_info['payment_method'] = self::getOrderPaymentMethod($order_info);
        if($order_info['goods_type'] == 1){
            $order_info['reward_coupons_id'] = Goods::merchantsObtainDiscountCoupons($order_info['goods_info']['reward_coupons_id']);
        }
        if($order_info['status'] == 1 && $order_info['deadline'] && $order_info['deadline'] < time()){
            $order_info['status'] = 4;
        }
        if($order_info['status'] == 1){
            $order_info['pay_time'] = date('Y-m-d H:i:s', $order_info['deadline']).'前可使用';
        }

        switch ($order_info['status']){
            case 1://已兑换
                $order_info['status_date_text'] = date('Y-m-d H:i:s', $order_info['deadline']).'前可使用';
                break;
            case 2://已使用
            case 3://已过期
                $order_info['status_date_text'] = date('Y-m-d H:i:s', $order_info['use_time']).'失效';
                break;
            case 4://已退还
                $order_info['status_date_text'] = date('Y-m-d H:i:s', $order_info['refund_time']).'退还';
                break;
        }
        /*refund_time*/
        return $order_info;
    }

    public static function usersExchangeChargeback($order_id){
        $field = 'id,order_no,goods_type,goods_id,goods_id as goods_info,payment_type,point_amount,
        youth_amount,status,pay_status,pay_time,deadline,distribute,users_id,goods_name as name,id as order_id';
        if(!$order_info = self::field($field)->where('id', $order_id)->find()){
            return ['code' => 0, 'msg' => '订单不存在', 'data' => []];
        }
        if($order_info['status'] != 1){
            return ['code' => 0, 'msg' => '订单状态异常', 'data' => []];
        }
        if($order_info['status'] == 1 && $order_info['deadline'] && $order_info['deadline'] < time()){
            return ['code' => 0, 'msg' => '商品已过期，无法申请返还', 'data' => []];
        }
        Db::startTrans();
        /*优惠劵*/
        if($order_info['goods_type'] == 1){
            if(!$distribute = XypHelper::formatJsonStringToArray($order_info['distribute'])){
                Db::rollback();
                return ['code' => 0, 'msg' => '返还失败1', 'data' => []];
            }
            if(!$coupons_id = (isset($distribute['record_id'])?$distribute['record_id']:0)){
                Db::rollback();
                return ['code' => 0, 'msg' => '返还失败2', 'data' => []];
            }
            if(!$coupons = UsersMarketingCoupons::getUsersCouponsInfo($order_info['users_id'], $coupons_id)){
                Db::rollback();
                return ['code' => 0, 'msg' => '返还失败3', 'data' => []];
            }
            if($coupons['use_status'] == 1 || $coupons['deadline_time'] < time()){
                Db::rollback();
                return ['code' => 0, 'msg' => '返还失败4','data' => []];
            }
            $coupons->grant_status = 10;
            $coupons->status = 10;
            $coupons->use_status = 2;
            $coupons->use_time = time();
            $coupons->save();
            /*设置优惠劵过期*/
        }
        $payment_info = self::increaseUsersPaymentInformation($order_info, $order_info['users_id']);
        if(!isset($payment_info['stated']) || !$payment_info['stated']){
            Db::rollback();
            return ['code' => 0, 'msg' => '返还失败5', 'data' => []];
        }
        if(!self::setOrdersPaymentChargeback($order_info)){
            Db::rollback();
            return ['code' => 0, 'msg' => '返还失败6', 'data' => []];
        }

        Db::commit();
        return ['code' => 1, 'msg' => '返还成功', 'data' => []];
    }

    public static function usersExchangeEnvelopes($order_id)
    {
        $field = 'id,order_no,goods_type,goods_id,goods_id as goods_info,payment_type,point_amount,
        youth_amount,status,pay_status,pay_time,deadline,distribute,users_id,goods_name as name,id as order_id';
        if(!$order_info = self::field($field)->where('goods_type', 2)->where('id', $order_id)->find()){
            return ['code' => 0, 'msg' => '订单不存在', 'data' => []];
        }
        if($order_info['status'] != 1){
            return ['code' => 0, 'msg' => '订单状态异常', 'data' => []];
        }
        if($order_info['status'] == 1 && $order_info['deadline'] && $order_info['deadline'] < time()){
            return ['code' => 0, 'msg' => '商品已过期，无法使用', 'data' => []];
        }
        $field = 'id,order_no,goods_type,goods_id,goods_id as goods_info,payment_type,point_amount,';
        Goods::field()->where()->find();
        Db::startTrans();
        /*优惠劵*/
        if($order_info['goods_type'] == 1){
            if(!$distribute = XypHelper::formatJsonStringToArray($order_info['distribute'])){
                Db::rollback();
                return ['code' => 0, 'msg' => '返还失败1', 'data' => []];
            }
            if(!$coupons_id = (isset($distribute['record_id'])?$distribute['record_id']:0)){
                Db::rollback();
                return ['code' => 0, 'msg' => '返还失败2', 'data' => []];
            }
            if(!$coupons = UsersMarketingCoupons::getUsersCouponsInfo($order_info['users_id'], $coupons_id)){
                Db::rollback();
                return ['code' => 0, 'msg' => '返还失败3', 'data' => []];
            }
            if($coupons['use_status'] == 1 || $coupons['deadline_time'] < time()){
                Db::rollback();
                return ['code' => 0, 'msg' => '返还失败4','data' => []];
            }
            $coupons->grant_status = 10;
            $coupons->status = 10;
            $coupons->use_status = 2;
            $coupons->use_time = time();
            $coupons->save();
            /*设置优惠劵过期*/
        }
        $payment_info = self::increaseUsersPaymentInformation($order_info, $order_info['users_id']);
        if(!isset($payment_info['stated']) || !$payment_info['stated']){
            Db::rollback();
            return ['code' => 0, 'msg' => '返还失败5', 'data' => []];
        }
        if(!self::setOrdersPaymentChargeback($order_info)){
            Db::rollback();
            return ['code' => 0, 'msg' => '返还失败6', 'data' => []];
        }

        Db::commit();
        return ['code' => 1, 'msg' => '返还成功', 'data' => []];
    }

    public static function processingUsersPaymentInformation($goods, $users_id)
    {
        $response = [
            'stated'    => false,
            'payment'   => [],
            'step'      => 0,
        ];
        $memo = '兑换'.$goods['name'];
        try {
            $res = false;
            if(in_array($goods['payment_type'], [1, 3])){
                $res = UsersModel::decreaseUserCurrency($users_id, $goods['point_amount'], 'score',$memo);
            }
            if(in_array($goods['payment_type'], [2, 4])){
                $res = UsersModel::decreaseUserCurrency($users_id, $goods['youth_amount'], 'youth_coin', $memo);
            }
            $response['stated'] = $res;
            if(!in_array($goods['payment_type'], [3, 4, 5])){
                $response['step'] = 1;
            }
            /*TODO 增加支付信息*/
            return $response;
        }catch (Exception $e){
            return $response;
        }
    }

    public static function increaseUsersPaymentInformation($goods, $users_id)
    {
        $response = [
            'stated'    => false,
            'payment'   => [],
            'step'      => 1,
        ];
        $memo = '兑换'.$goods['name'] .'-退回';
        try {
            $res = false;
            if(in_array($goods['payment_type'], [1, 3])){
                $res = UsersModel::increaseUserCurrency($users_id, $goods['point_amount'], 'score',$memo);
            }
            if(in_array($goods['payment_type'], [2, 4])){
                $res = UsersModel::increaseUserCurrency($users_id, $goods['youth_amount'], 'youth_coin', $memo);
            }
            $response['stated'] = $res;
            if(!in_array($goods['payment_type'], [3, 4, 5])){
                $response['step'] = 1;
            }
            /*TODO 增加退款信息*/
            return $response;
        }catch (Exception $e){
            return $response;
        }
    }

    public static function setOrdersPaymentSuccessful($goods)
    {
        if(!isset($goods['order_id']) || !$goods['order_id']){
            return false;
        }
        $forms = [
            'status'           => 1,
            'pay_status'       => 10,
            'distribute'       => (isset($goods['distribute'])?XypHelper::formatArrayToString($goods['distribute']):''),
            'updatetime'       => time(),
            'pay_time'         => time(),
            'pay_no'           => XypHelper::xyb_get_order_no()
        ];
        return self::where('id', $goods['order_id'])->update($forms);
    }

    public static function setOrdersPaymentChargeback($goods)
    {
        $forms = [
            'status'      => 3,
            'distribute'  => (isset($goods['distribute'])?XypHelper::formatArrayToString($goods['distribute']):''),
            'updatetime'  => time(),
            'refund_time' => time(),
            'refund_no'   => XypHelper::xyb_get_order_no()
        ];
        return self::where('id', $goods['order_id'])->update($forms);
    }

    public static function setOrdersPaymentUses($attach)
    {
        if(!$attach = XypHelper::formatJsonStringToArray($attach)){
            return false;
        }
        if(!$order_id = (isset($attach['order_id'])?$attach['order_id']:0)){
            return false;
        }
        $forms = ['status' => 2, 'updatetime' => time(), 'use_time' => time()];
        return self::where('id', $order_id)->update($forms);
    }

    private static function getOrderPaymentMethod($order){
        $payment_method = '';
        if (in_array($order['payment_type'], [1, 3])){
            $payment_method = floatval($order['point_amount']).'积分';
        }
        if (in_array($order['payment_type'], [2, 4])){
            $payment_method = floatval($order['youth_amount']).'青年币';
        }
        if (in_array($order['payment_type'], [3, 4, 5])){
            $payment_method = ($payment_method?'+':'').floatval($order['purchase_amount']).'元';
        }
        return $payment_method;
    }
}
